#!/bin/bash
# Git Bash编译脚本 - 使用Unix风格路径避免空格问题

# 转换Windows路径为Unix风格
MAKE_PATH="/c/Program\ Files\ \(x86\)/GnuWin32/bin/make.exe"
ARM_GCC="/d/arm-gnu-toolchain-14.3.rel1-mingw-w64-i686-arm-none-eabi/bin/arm-none-eabi-gcc.exe"
ARM_GXX="/d/arm-gnu-toolchain-14.3.rel1-mingw-w64-i686-arm-none-eabi/bin/arm-none-eabi-g++.exe"
ARM_AS="/d/arm-gnu-toolchain-14.3.rel1-mingw-w64-i686-arm-none-eabi/bin/arm-none-eabi-gcc.exe"
ARM_OBJCOPY="/d/arm-gnu-toolchain-14.3.rel1-mingw-w64-i686-arm-none-eabi/bin/arm-none-eabi-objcopy.exe"
ARM_AR="/d/arm-gnu-toolchain-14.3.rel1-mingw-w64-i686-arm-none-eabi/bin/arm-none-eabi-ar.exe"
ARM_SIZE="/d/arm-gnu-toolchain-14.3.rel1-mingw-w64-i686-arm-none-eabi/bin/arm-none-eabi-size.exe"

# 验证工具是否存在
echo "验证编译工具..."
if [ ! -f "$MAKE_PATH" ]; then
    echo "错误: 未找到make工具，请检查路径是否正确"
    echo "路径: $MAKE_PATH"
    exit 1
fi

if [ ! -f "$ARM_GCC" ]; then
    echo "错误: 未找到ARM工具链，请检查路径是否正确"
    echo "路径: $ARM_GCC"
    exit 1
fi

# 创建build目录
if [ ! -d "build" ]; then
    mkdir -p build
fi

# 执行编译，通过Makefile变量覆盖工具路径
echo -e "\n开始编译ODrive固件..."
echo "使用make: $MAKE_PATH"
echo "使用ARM工具链: $(dirname $ARM_GCC)"

"$MAKE_PATH" CC="$ARM_GCC" CXX="$ARM_GXX" AS="$ARM_AS -x assembler-with-cpp" CP="$ARM_OBJCOPY" AR="$ARM_AR" SZ="$ARM_SIZE" -j4

# 检查结果
if [ $? -eq 0 ]; then
    echo -e "\n编译成功!"
    echo "输出文件在build目录:"
    ls -la build/*.elf build/*.hex build/*.bin 2>/dev/null || echo "未找到输出文件"
else
    echo -e "\n编译失败，请查看错误信息"
fi